#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# f = open("a.txt", "r", encoding="utf-8")  # 指定默认的字符集
# data = f.read()
# data = f.readline()
# print(data)
# print(f.readlines())        # ['hello world - 1\n', 'hello world - 2\n',...]
# for li in f.readline():
#     print(li)
# f.close()


# f = open("a.txt", "rb")  # 指定默认的字符集
# # print(f.readlines())
# print(f.seek(10, 1))
# print(f.read().decode('utf-8').split("\r\n"))
# f.close()

# f = open("a.txt", "rt")
# print(f.read(3))  # 只取三个字符
# print(f.read())  # 全部取出，然后一次打印
# print(f.readable())

# print(f.readline())  # 只打印一行
# for i in f.readlines():
#     print(i.strip())

# f.close()


# with open("a.txt", "r") as f:
#     for i in f.readlines():
#         print(i.strip())

# 全部取出到内存中，但是没有修改原文件
# with open("a.txt", "rt", encoding="utf-8") as f:
#     msg = f.read()
#     msg = msg.replace("1", "a")
#     print(msg)
import os
with open("a.txt", "rt", encoding="utf-8") as read_f,\
        open(".a.txt.swap", "wt", encoding="utf-8") as write_f:
    for read in read_f:
        read_f.seek(0,0)  # 先移到最开始
        msg = read_f.read()  # 一行一行取
        change= msg.replace("2222","a")  #然后单个删除
        write_f.write(change)           # 将修改后的文件放到新的文件中
        print(read_f.tell())            # 98
        print(write_f.tell())       # 83

os.remove("a.txt")
os.rename(".a.txt.swap", "a.txt")

# with open("a.txt", "r+b") as f:
#     f.seek(0, 2)   # 到文件未尾
#     f.write(b"\nhello world")  # 追加hello world
#     f.seek(0, 2)   # 到文件未尾
#
#     print(f.read(f.tell()))
